package com.scut.chenlujie.library.clink.core;

import java.io.IOException;

//封装了channel那一块
public class IoContext {
    private static IoContext INSTANCE;
    //针对所有连接的
    private final IoProvider ioProvider;


    private final Scheduler scheduler;

    public IoContext(IoProvider ioProvider, Scheduler scheduler) {
        this.ioProvider = ioProvider;

        this.scheduler = scheduler;
    }
    public Scheduler getScheduler() {
        return scheduler;
    }

    public IoProvider getIoProvider() {
        return ioProvider;
    }

    public static IoContext get() {
        return INSTANCE;
    }

    public static StartedBoot setup(){
        return new  StartedBoot();
    }

    public static void close() throws  IOException {
        if(INSTANCE != null){
            INSTANCE.callClose();
        }
    }

    public void callClose() throws IOException {
        ioProvider.close();
        scheduler.close();
    }

    //一个启动引导类 IoContext.setup().ioProvider(ioProvider).start() 这样子就返回了IoContext实例
    //外界没有办法直接new Iocontext() 因为这个是private的
    public static class StartedBoot {
        private IoProvider ioProvider;
        private Scheduler scheduler;

        private StartedBoot(){

        }
        public StartedBoot ioProvider(IoProvider ioProvider){
            this.ioProvider = ioProvider;
            return this;
        }
        public StartedBoot scheduler(Scheduler scheduler){
            this.scheduler = scheduler;
            return this;
        }

        public IoContext start() {
            INSTANCE = new IoContext(ioProvider, scheduler );
            return INSTANCE;
        }
    }
}
